package com.myself.ssoserver.controller

import com.myself.ssoserver.dto.AuthRequest
import com.myself.ssoserver.dto.AuthResponse
import com.myself.ssoserver.dto.SimpleRegisterRequest
import com.myself.ssoserver.service.AuthService
import com.myself.ssoserver.service.UserService
import jakarta.servlet.http.HttpServletRequest
import org.redisson.api.RedissonClient
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*

@RestController
@RequestMapping("/api/auth")
class AuthController(
    private val userService: UserService,
    private val authService: AuthService,
    private val redisson: RedissonClient
) {
    companion object {
        private const val TOKEN_PREFIX = "sso:token:"
        private const val EXPIRATION_MINUTES = 30L
    }
    @PostMapping("/login")
    fun login(
        @RequestBody request: AuthRequest,
        requestContext: HttpServletRequest
    ): AuthResponse {
        val clientIp = requestContext.remoteAddr
        val userAgent = requestContext.getHeader("User-Agent")

        return authService.login(request, clientIp, userAgent)
    }

    @GetMapping("/logout")
    fun logout(@RequestHeader("Authorization") token: String){
        val cleanToken = token.substringAfter("Bearer ")
        redisson.getBucket<Any>("$TOKEN_PREFIX$cleanToken").delete()
    }

    @PostMapping("/simple-register")
    fun simpleRegister(@RequestBody request: SimpleRegisterRequest) {
        val user = userService.simpleRegister(request)
    }
}